// pages/my/bindTel/bindTel.js
import {
    ajaxPost,
    showToast
} from '../../../utils/util.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        phone: '',
        code: '',
        time: 60,
        change: false,
        smscode:'',
        isClick:0
    },

    /**
     * 输入电话
     */
  
    inputPhone(e) {
        var inputphone = e.detail.value;
        this.setData({
            phone: inputphone
        })
    },
       /**
     * 输入验证码
     * @param {*} e 
     */
    inputCode(e) {
        var inputcode = e.detail.value;
        this.setData({
            code: inputcode
        })
    },
       /**
     * 提交
     * @param {*} e 
     */
    submitValue() {
        var code = Number(this.data.code);
        var smscode = Number(this.data.smscode);
        var phone = Number(this.data.phone);
        var isClick = this.data.isClick;
        var reg = /^1[0-9]{10}$/;
        if (!reg.test(phone)) {
            return showToast('text', "请输入正确手机号")
        }
        if(code !== smscode){
            return showToast('text',"请输入正确验证码")
        }
        if(isClick == 0){
            return showToast('text',"请先获取验证码")
        }
        if(code == ''){
            return showToast('text',"请输入正确验证码")
        }

        let data = {
            mobile: phone
        }
        ajaxPost('member/save_mobile',data,res=>{
            if(res.code == 0){
                showToast('text', "绑定成功")
                setTimeout(() => {
                    wx.navigateBack({
                        delta: 1,
                    })
                }, 1000)
            }else{
                showToast('text', res.msg)
                return
            }
        })

       
    },
       /**
     * 获取验证码
     * @param {*} e 
     */
    getCode() {
        var phone = Number(this.data.phone);
        var isClick = this.data.isClick;
        var reg = /^1[0-9]{10}$/;
        if (!reg.test(phone)) {
            return showToast('text', "请输入手机号")
        }
        let data = {
            mobile: phone
        }
        ajaxPost('member/sms', data, res => {
            if (res.code == 40020) {
                return showToast('text', res.msg)
            } else {
                showToast('text',"短信发送成功!")
                isClick = isClick + 1
                this.timeChange()
                this.setData({
                    change: true,
                    smscode: res.code,
                    isClick:isClick
                })
            }
        })
    },
       /**
     * 倒计时
     * @param {*} e 
     */
    timeChange() {
        var time = this.data.time;
        var interval = setInterval(() => {
            if (time == 0) {
                clearInterval(interval)
                this.setData({
                    change: false
                })
                return
            }
            time = time - 1
            this.setData({
                time: time
            })
        }, 1000)
    }
})